import React, { useState, useEffect, useRef } from 'react';

import { Field, useService } from '@flowgram.ai/free-layout-editor';
import { DynamicValueInput } from '@flowgram.ai/form-materials';

import { fetchRemoteOptions, RemoteOptionType } from '@/services/remote-options-service';
import { OptionItem } from '@/components/ui/combobox';
import { Combobox } from '@/components/ui/combobox';

import { FormItem } from '../form-item';
import { Feedback } from '../feedback';
import { JsonSchema } from '../../typings';
import { CustomService } from '../../services/custom-service';
import { useNodeRenderContext } from '../../hooks';

// 添加远程选项支持的动态输入组件
const DynamicInputWithRemoteOptions = ({ property, field, fieldState, readonly }) => {
  const [options, setOptions] = useState<OptionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const customService = useService(CustomService);
  const isMounted = useRef(false); // Track if component is mounted

  // Set mounted state
  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  useEffect(() => {
    const controller = new AbortController(); // Create abort controller
    if (property.remoteOptions) {
      setLoading(true);
      // 根据错误提示，`CustomService` 上不存在 `fetchRemoteOptions` 属性，需使用正确的方法名
      // 此处假设正确的方法名为 `fetchOptions`，实际应根据 `CustomService` 定义修改
      fetchRemoteOptions(property.remoteOptions as RemoteOptionType, controller.signal)
        .then((options) => {
          if (isMounted.current) {
            setOptions(options);
            console.log('Fetched options:', options);
          }
        })
        .catch((err) => {
          if (!controller.signal.aborted) {
            console.error('Error loading options:', err);
          }
        })
        .finally(() => {
          if (isMounted.current) {
            setLoading(false);
          }
        });
    }

    return () => {
      isMounted.current = false;
      controller.abort();
    };
  }, [property.remoteOptions, customService]);

  function onChange(value: number) {
    field.onChange({
      type: 'constant',
      content: value,
    });
    console.log('onChange', field.value.content);
  }

  return (
    <>
      {loading ? (
        <div>Loading models...</div>
      ) : property.remoteOptions && options.length > 0 ? (
        <Combobox
          frameworks={options}
          value={field.value?.content ?? 0}
          defaultValue={0}
          onChange={onChange}
        />
      ) : (
        <DynamicValueInput
          value={field.value}
          onChange={field.onChange}
          readonly={readonly || loading}
          hasError={Object.keys(fieldState?.errors || {}).length > 0}
          schema={property}
        />
      )}
    </>
  );
};

export function FormInputs() {
  const { readonly } = useNodeRenderContext();
  return (
    <Field<JsonSchema> name="inputs">
      {({ field: inputsField }) => {
        const required = inputsField.value?.required || [];
        const properties = inputsField.value?.properties;
        if (!properties) {
          return <></>;
        }
        const content = Object.keys(properties).map((key) => {
          const property = properties[key];
          return (
            <Field key={key} name={`inputsValues.${key}`} defaultValue={property.default}>
              {({ field, fieldState }) => (
                <FormItem
                  name={key}
                  type={property.type as string}
                  required={required.includes(key)}
                >
                  <DynamicInputWithRemoteOptions
                    property={property}
                    field={field}
                    fieldState={fieldState}
                    readonly={readonly}
                  />
                  <Feedback errors={fieldState?.errors} warnings={fieldState?.warnings} />
                </FormItem>
              )}
            </Field>
          );
        });
        return <>{content}</>;
      }}
    </Field>
  );
}
